import os
import subprocess
from typing import Set, Union

from pathspec import PathSpec
from pathspec.patterns.gitwildmatch import GitWildMatchPattern
import sys

sys.path.append(r"C:\Users\houzh\Developing\simple-text-search")
from TextSearch.utils import remove_gitignore


# def find_git_repositories(base_path):
#     """搜索指定路径下的所有git仓库"""
#     # git_repositories = []
#     for root, dirs, files in os.walk(base_path):
#         if ".gitignore" in files:
#             gitignore_path = os.path.join(root, ".gitignore")
#             # remove
#         if ".git" in dirs:
#             yield root
#             dirs.remove(".git")  # 避免递归进入.git目录


def find_git_repos_2(base_path, ignored_paths):
    if base_path in ignored_paths:
        yield from []

    def get_dirs_and_files(path) -> Union[Set[str], Set[str]]:
        files, dirs = set(), set()
        for item in os.listdir(path):
            item_abspath = os.path.join(path, item)
            if os.path.isdir(item_abspath):
                dirs.add(item)
            else:
                files.add(item)
        return dirs, files

    print("searching path", base_path, file=sys.stderr)

    dirs, files = get_dirs_and_files(base_path)
    if ".git" in dirs:
        yield base_path
        dirs.remove(".git")
    dirs.remove("node_modules")
    if ".gitignore" in files:
        gitignore_path = os.path.join(base_path, ".gitignore")
        dirs = remove_gitignore(gitignore_path, dirs)
    for i, dir in enumerate(dirs):
        if i < 1000: # 对子文件夹数量大于1000的文件夹，只搜索前1000个，避免循环次数过多
            yield from find_git_repos_2(os.path.join(base_path, dir), ignored_paths)


def get_remote_branches(repo_path):
    """获取git仓库的所有远程分支地址"""
    remote_branches = []
    command = ["git", "-C", repo_path, "remote", "-v"]
    result = subprocess.run(command, capture_output=True, text=True)
    if result.returncode == 0:
        for line in result.stdout.strip().split("\n"):
            parts = line.split()
            if len(parts) == 3 and parts[2] == "(fetch)":
                remote_branches.append((parts[0], parts[1]))
    return remote_branches


def main():
    base_path = r"C:\Users\houzh\Developing"
    ignored_paths = [
        r"C:\Users\houzh\Developing\yy\2022-08-11-juliet-c-cplusplus-v1-3-1-with-extra-support"
    ]
    # git_repositories =

    for i, repo_path in enumerate(find_git_repos_2(base_path, ignored_paths)):
        print(f"Git仓库#{i+1}: {os.path.basename(repo_path)}")
        print(f"本地路径: {repo_path}")
        remote_branches = get_remote_branches(repo_path)
        for remote, url in remote_branches:
            print(f"  远程分支地址: {remote} - {url}")
        print()


if __name__ == "__main__":
    main()
